package com.whsxt.sys.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whsxt.common.CodeMsg;
import com.whsxt.common.PageInfo;
import com.whsxt.common.Result;
import com.whsxt.common.util.ConstantUtil;
import com.whsxt.common.util.Md5Util;
import com.whsxt.common.util.PinYinUtil;
import com.whsxt.common.util.WebContextUtil;
import com.whsxt.sys.common.ResultObject;
import com.whsxt.sys.data.UserData;
import com.whsxt.sys.domain.Dept;
import com.whsxt.sys.domain.Logininfo;
import com.whsxt.sys.domain.Role;
import com.whsxt.sys.domain.User;
import com.whsxt.sys.service.IDeptService;
import com.whsxt.sys.service.ILogininfoService;
import com.whsxt.sys.service.IRoleService;
import com.whsxt.sys.service.IUserService;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 贺炯
 * @since 2019-09-20
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {
	
	@Autowired
	private ILogininfoService iLogininfoService;
	
	@Autowired
	private IUserService iUserService;
	
	@Autowired
	private IDeptService iDeptService;
	
	@Autowired
	private IRoleService iRoleService;
	/**
	 * 	查询 用户列表
	 * @param data
	 * @return
	 */
	@RequestMapping("/list")
	public Object list(UserData data) {
		IPage<User> page = new Page<User>(data.getPage(),data.getLimit());
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq(data.getDeptid()!=null&&data.getDeptid()!= ' ', "deptid", data.getDeptid());
		queryWrapper.like(StrUtil.isNotBlank(data.getName()),"name", data.getName());
		queryWrapper.like(StrUtil.isNotBlank(data.getAddress()),"address",data.getAddress());
		queryWrapper.eq("available", ConstantUtil.AVAILABLE_TRUE);
		iUserService.page(page, queryWrapper);
		List<User> records = page.getRecords();
		for (User user : records) {
			Integer deptid = user.getDeptid();
			if(deptid != null) {
				//给 新增的部门名称 赋值
				Dept dept = iDeptService.getById(deptid);
				user.setDeptname(dept.getTitle());
			}
			Integer mgr = user.getMgr();
			if(mgr!=null) {
				//给 新增的 领导姓名 辅助
				User user2 = iUserService.getById(mgr);
				user.setLeadername(user2.getName());
			}
		}
		PageInfo pageInfo = new PageInfo(page.getTotal(), records);
		return new Result(pageInfo);
	} 
	/**
	 * 	获取排序编号
	 * @return
	 */
	@RequestMapping("/getOrdernum")
	public Object getOrdernum() {
		Map<String, Object> map = new HashMap<String, Object>();
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.orderByDesc("ordernum");
		IPage<User> page = new Page<User>(1, 1);
		iUserService.page(page , queryWrapper);
		List<User> records = page.getRecords();
		if(records.size()>0) {
			map.put("value",records.get(0).getOrdernum()+1);
		}else {
			map.put("value", 1);
		}
		return map;
	}
	/**
	 * 	查询当前部门下面的所有用户
	 * @param deptId
	 * @return
	 */
	@RequestMapping("/getLeaderName")
	public Object getLeaderName(Integer deptId) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq("type",ConstantUtil.USER_TYPE_COMMON);
		queryWrapper.eq(deptId != ' '&&deptId != null, "deptid", deptId);
		queryWrapper.eq("available", ConstantUtil.AVAILABLE_TRUE);
		List<User> list = iUserService.list(queryWrapper);
		return new Result(list);
	}
	/**
	 *  将用户姓名装换成拼音
	 * @param name
	 * @return
	 */
	@RequestMapping("/pinyin")
	public Map<String,Object> pinyin(String name){
		Map<String , Object> map = new HashMap<String, Object>();
		if(StrUtil.isNotBlank(name)) {
			String pingYin = PinYinUtil.getPingYin(name);
			System.out.println(pingYin);
			map.put("value", pingYin);
		}else {
			map.put("value", "");
		}
		return map;
	}
	
	/**
	 *  新增用户
	 * @param data
	 * @return
	 */
	@RequestMapping("/addUser")
	public Object addUser(UserData data) {
		data.setType(ConstantUtil.USER_TYPE_COMMON);
		data.setHiredate(new Date());
		String salt = IdUtil.simpleUUID();
		data.setSalt(salt);
		String pwd = Md5Util.getMd5Data(ConstantUtil.USER_DEFAULT_PASSWORD, 2, salt);
		data.setPwd(pwd);
		
		try {
			iUserService.save(data);
			return new Result(CodeMsg.USER_ADD_SECCUSS);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(CodeMsg.USER_ADD_ERROR);
		}
	}
	/**
	 *    根据id查找对应的用户
	 * @param id
	 * @return
	 */
	@RequestMapping("/getUserById")
	public Object getUserById(Integer id) {
		User user = null;
		if(id != null && id != ' ') {
			user = iUserService.getById(id);
		}else {
			user = new User();
		}
		return new Result(user);
	}
	/**
	 * 	更新用户信息       有一个问题就是 可以选自己作为自己的直属领导人
	 * @param user
	 * @return
	 */
	@RequestMapping("/updateUser")
	public Object updateUser(User user) {
		try {
			iUserService.updateById(user);
			return new Result(CodeMsg.USER_UPDATE_SECCUSS);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(CodeMsg.USER_UPDATE_ERROR);
		}
	}
	/**
	 * 根据用户id 删除用户
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteOne")
	public Object deleteOne(Integer id) {
		try {
			iUserService.removeById(id);
			return new Result(CodeMsg.USER_DELETE_SECCUSS);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(CodeMsg.USER_DELETE_ERROE);
		}
	}
	/**
	 * 	重置密码   原始密码为 123456
	 * @param id
	 * @return
	 */
	@RequestMapping("/resetPassword")
	public Object resetPassword(Integer id) {
		User user = new User();
		user.setId(id);
		String salt = IdUtil.simpleUUID();
		user.setSalt(salt);
		String pwd = Md5Util.getMd5Data(ConstantUtil.USER_DEFAULT_PASSWORD, 2, salt);
		user.setPwd(pwd);
		try {
			iUserService.updateById(user);
			return new Result(CodeMsg.UPDATE_PASSWORD_SECCUSS);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(CodeMsg.UPDATE_PASSWORD_ERROR);
		}
	}
	
	/**
	 *    初始化角色表单 并 选择当前用户已拥有的角色
	 *    
	 * @return
	 */
	@RequestMapping("/initRole")
	public Object initRole(Integer id) {
		//查询所有角色
		QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>();
		queryWrapper.eq("available",ConstantUtil.AVAILABLE_TRUE);
		List<Map<String, Object>> listMaps = iRoleService.listMaps(queryWrapper);
		//查询当前用户id拥有的角色
		List<Integer> roleList =  iRoleService.selectRidByUid(id);
		for (Map<String, Object> map : listMaps) {
			Integer roleid = (Integer) map.get("id");
			//增加该属性 只有 LAY_CHECKED = true 即为选中状态
			Boolean LAY_CHECKED=false;
			for (Integer integer : roleList) {
				if(roleid == integer) {
					LAY_CHECKED = true;
				}
			}
			map.put("LAY_CHECKED", LAY_CHECKED);
		}		
		PageInfo pageInfo = new PageInfo(Long.valueOf(listMaps.size()), listMaps);
		return new Result(pageInfo);
	}
	/**
	 * 	 给用户添加角色   在用户角色表中插入数据
	 * @param uid
	 * @param rid
	 * @return
	 */
	@RequestMapping("/insertRidUid")
	public Object insertRidUid(Integer uid,Integer[] rid) {
		try {
			iRoleService.insertRidUid(uid,rid);
			return new Result(CodeMsg.INSERT_USER_ROLE_SECCUSS);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(CodeMsg.INSERT_USER_ROLE_ERROR);
		}
	}
	
	
	/**
	 * 	生成验证码
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/checkCode")
	public void checkCode(HttpServletResponse response) throws IOException {
		CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(116, 36, 4, 5);
		String code = captcha.getCode();
		HttpSession session = WebContextUtil.getSession();
		session.setAttribute("checkCode", code);
		System.out.println(code);
		ServletOutputStream outputStream = response.getOutputStream();
		captcha.write(outputStream);
		outputStream.close();
	}
	/**
	 * 	 登录shiro认证	
	 * @param username
	 * @param password
	 * @param checkCode
	 * @return
	 */
	@RequestMapping("/login")
	public Object login(String username,String password,String checkCode) {
		HttpSession session = WebContextUtil.getSession();
		String code = session.getAttribute("checkCode").toString();
		if(!checkCode.equalsIgnoreCase(code)) {
			return new Result(CodeMsg.CHECKCODE_ERROR);
		}
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(username, password);
		try {
			subject.login(token);
			ResultObject ro = (ResultObject) subject.getPrincipal();
			User user = ro.getUser();
			session.setAttribute("currUser", user);
			Logininfo entity = new Logininfo();
			entity.setLoginip(WebContextUtil.getRequest().getRemoteAddr());
			entity.setLoginname(user.getName()+"-"+user.getLoginname());
			entity.setLogintime(new Date());
			iLogininfoService.save(entity);
			return new Result(CodeMsg.SECCUSS);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			return new Result(CodeMsg.USERNAME_PASSWORD_ERROR);
		}
	}
	/**
	 * 修改用户信息
	 * @param user
	 * @param province
	 * @param city
	 * @param area
	 * @return
	 */
	@RequestMapping("/changeUser")
	public Object changeUser(User user,String province,String city,String area) {
		String address = "";		
		if(StrUtil.isNotBlank(province)) {
			address+=province;
		}
		if(StrUtil.isNotBlank(city)) {
			address+="-"+city;
		}
		if(StrUtil.isNotBlank(area)) {
			address+="-"+area;
		}
		if(address.contains("请选择")) {
			address = address.substring(0, address.indexOf("请选择")-1);
		}
		User user2 = (User) WebContextUtil.getSession().getAttribute("currUser");
		user.setId(user2.getId());
		user.setAddress(address);
		try {
			iUserService.updateById(user);
			return new Result(CodeMsg.USER_UPDATE_SECCUSS);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(CodeMsg.USER_UPDATE_ERROR);
		}
	}
	/**
	 * 修改用户密码
	 * @param oldPassword
	 * @param newPassword
	 * @param newPassword1
	 * @return
	 */
	@RequestMapping("/changePassword")
	public Object changePassword(String oldPassword,String newPassword,String newPassword1) {
		if(!newPassword.equals(newPassword1)) {
			return new Result(CodeMsg.ThE_TWO_PASSWORD_DO_NOT_MATCH);
		}
		User user = (User) WebContextUtil.getSession().getAttribute("currUser");
		String md5Data = Md5Util.getMd5Data(oldPassword, 2,user.getSalt());
		if(!md5Data.equals(user.getPwd())) {
			return new Result(CodeMsg.OLD_PASSWORD_ERROR);
		}
		String md5Data2 = Md5Util.getMd5Data(newPassword, 2, user.getSalt());
		user.setPwd(md5Data2);
		try {
			iUserService.updateById(user);
			WebContextUtil.getSession().removeAttribute("currUser");
			return new Result(CodeMsg.UPDATE_PASSWORD_SECCUSS);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(CodeMsg.UPDATE_PASSWORD_ERROR);
		}
	}
	/**
	 * 用户退出 将session信息
	 * @return
	 */
	@RequestMapping("/loginOut")
	public Object loginOut() {
		WebContextUtil.getSession().removeAttribute("currUser");
		Result rs = new Result();
		return rs;
	}
}

